﻿using LeEdu.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeEdu.DAL.DataAccess
{
    using ServiceStack.OrmLite;

    public class NodeDal:GenericBaseDAL<Node>
    {
        /// <summary>
        /// 获取课程课时类表（带排序）
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public List<Node> GetNodeListByOrder(Guid uid)
        {
            using (var cnn=DbConnection)
            {
                var sql = cnn.From<Node>()
                    .Where(m => m.CourseId == uid)
                    .OrderBy(m => m.Order);

                return cnn.Select(sql);
            }
        }

        public bool UpdateNodeSort(string[] ids)
        {
            List<Node> nodes = new List<Node>();
            Node node;
            for (int i = 0; i < ids.Length; i++)
            {
                var str = ids[i];
                var id = str.Substring(str.IndexOf('-') + 1);// str.Split(new char[] { '-' })[1];
                node = new Node();
                node.Id = new Guid(id);
                node.Order = i + 1;
                nodes.Add(node);
            }

            if(nodes.Count>0)
            {
                using (var cnn=DbConnection)
                {
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        cnn.UpdateOnly(nodes[i], m => new { m.Order },m=>m.Id==nodes[i].Id);
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 获取课程最大Order
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public int GetNodeLastOrder(Guid uid)
        {
            using (var cnn=DbConnection)
            {
                var sql = cnn.From<Node>()
                    .Where(m => m.CourseId == uid)
                    .Limit(1)
                    .OrderByDescending(m => m.Order);
                var result = cnn.Select(sql).FirstOrDefault<Node>();
                if(null!=result)
                {
                    return result.Order + 1;
                }
                else
                {
                    return 1;
                }
            }
        }
    }
}
